<script lang="ts" setup>

import {useRoute, useRouter} from "vue-router";
import {onMounted, ref, watch} from "vue";
import {useTopicStore} from "../../store/TopicStore.ts";
import type {TopicListData} from "../../network/types/Topic.ts";
import TopicTable from "../../components/topic/TopicTable.vue";
import {SearchContent, type TopicOrderBy} from "../../network/api/TopicApi.ts";
import {ElMessage} from "element-plus";
import {PostRouteName, ReplyListRoute, TopicListRoute} from "../index.ts";
import type {NgaResponse} from "../../network/types/NgaResponse.ts";
import {iconUrl, setWindowTitle, toNumber} from "../../utils/Utils.ts";
import {useForumStore} from "../../store/ForumStore.ts";
import {scrollShortKeys, type ShortKey, showShortKeys} from "../../utils/ShortKeys.ts";
import ForumIconName from "../../components/entrance/ForumIconName.vue";
import {ForumStatus} from "../../network/types/ForumStatus.ts";

const route = useRoute();
const router = useRouter();
const forumStore = useForumStore();
const topicStore = useTopicStore();


const goBack = () => window.history.back();
// 数据
const data = ref<TopicListData>()

// 版面id
const fid = ref<string>()
const stid = ref<number>()
const forumIcon = ref<string>()
const keyword = ref<string>()
const title = ref<string>()
const privilegeHtml = ref<string>()
// 页码
const page = ref<number>(1)
// 用户ID
const userId = ref<number>()
// 搜索时选中的版面ID
const checkList = ref<number[]>()
// 排序方式
const orderBy = ref<TopicOrderBy>()
const content = ref<SearchContent>()
const recommend = ref<1 | 0>()
//  加载中
const loading = ref(false)
// 显示子版块弹窗
const showSubForumDialog = ref(false)
// 显示被屏蔽主题弹窗
const showBlockedTopicDialog = ref(false)
const showPrivilegeDialog = ref(false)

// 同步参数
const syncParams = () => {
  fid.value = route.params.fid?.toString() || route.query.fid?.toString()
  stid.value = route.params.stid ? Number(route.params.stid) : undefined
  userId.value = route.params.userId ? Number(route.params.userId) : undefined
  keyword.value = route.params.keyword?.toString()
  orderBy.value = route.query.orderBy as TopicOrderBy
  content.value = route.query.content ? Number(route.query.content) as SearchContent : SearchContent.Title
  recommend.value = Number(route.query.recommend) ? 1 : 0
  page.value = route.query.page ? Number(route.query.page) : 1
  checkList.value = fid.value?.split(",")?.map(Number) || []

  forumIcon.value = iconUrl(Number(fid.value)) || iconUrl(Number(stid.value))
}

const favorAdd = (fid?: number | undefined, stid?: number | undefined) => {
  forumStore.favorAdd(fid, stid).then(res => {
    ElMessage.success(res)
    forumStore.favorList(true)
  }).catch(r => {
    console.error(r)
    if (r.error) {
      ElMessage.error(r.error[0])
    }
  })
}

const privilege = () => {
  const id = toNumber(fid.value)
  if (id) {
    topicStore.privilege(id).then(res => {
      privilegeHtml.value = res
      showPrivilegeDialog.value = true
    })
  }
}
const favorDel = (fid?: number | undefined, stid?: number | undefined) => {
  forumStore.favorDel(fid, stid).then(res => {
    ElMessage.success(res)
    forumStore.favorList(true)
  }).catch(r => {
    console.error(r)
    if (r.error) {
      ElMessage.error(r.error[0])
    }
  })
}

// 发送请求
const request = async (route: any, force: boolean) => {
  loading.value = true

  syncParams()


  try {
    switch (route.name) {
      case TopicListRoute.FORUM_LIST:
        data.value = await topicStore.forumList(Number(fid.value), page.value, orderBy.value, force);
        break;
      case TopicListRoute.FORUM_SEARCH:
        data.value = await topicStore.forumSearch(keyword.value!!, fid.value!!, page.value, content.value, recommend.value, force);
        break;
      case TopicListRoute.FORUM_RECOMMEND:
        data.value = await topicStore.forumRecommend(Number(fid.value), page.value, force);
        break;
      case TopicListRoute.COL_LIST:
        data.value = await topicStore.colList(Number(stid.value), page.value, orderBy.value, force);
        break;
      case TopicListRoute.COL_SEARCH:
        data.value = await topicStore.colSearch(keyword.value!!, stid.value!!, page.value, content.value, recommend.value, force);
        break;
      case TopicListRoute.USER_REPLIES:
        data.value = await topicStore.userReplies(userId.value!!, fid.value ? Number(fid.value) : undefined, page.value, force);
        break;
      case TopicListRoute.USER_TOPIC:
        data.value = await topicStore.userTopic(userId.value!!, fid.value ? Number(fid.value) : undefined, recommend.value, page.value, force);
        break;
    }
    title.value = data.value?.colName || data.value?.forumName
    title.value && setWindowTitle(title.value)
    console.debug(data.value)
  } catch (e: any) {
    if (e.error as NgaResponse<any>) {
      ElMessage.error(`${e.error.code}:${e.error.message}`)
    }
    console.warn(e)
    goBack()
  }
  loading.value = false
};
// 切换页数
const changePage = (p: number | undefined) => {
  if (!p) return
  page.value = p
  return router.push({query: {...route.query, page: p}, params: route.params});
}
// 以当前页为基准翻页
const pageOffset = (offset: number) => {
  const p = page.value
  const total = data.value?.totalPage

  // 不符合要求，不执行
  if (!p || !total) return

  const target = p + offset
  if (target > 0 && target <= total) {
    changePage(target)
  }
}
// 跳转到到版面或合集
const routeToForum = () => {
  if (data.value?.colTid) {
    router.push({name: TopicListRoute.COL_LIST, params: {stid: data.value?.colTid}})
  } else {
    router.push({name: TopicListRoute.FORUM_LIST, params: {fid: route.params.fid}})
  }
}
// 跳转到精华区
const routeToRecommend = () => router.push({name: TopicListRoute.FORUM_RECOMMEND, params: {fid: route.params.fid}})
// 跳转到搜索结果
const routeToSearch = () => {
  return router.push({
    name: TopicListRoute.FORUM_SEARCH, params: {
      keyword: keyword.value,
      fid: checkList.value?.join(',') || "",
    }, query: {
      content: content.value,
      recommend: recommend.value,
    }
  });
}
// 刷新
const refresh = () => request(route, true)
// 跳转到新帖界面
const routeToPost = (fid: string | undefined, stid: number | undefined) => {
  router.push({name: PostRouteName, params: {action: 'new'}, query: {stid, fid}})
}
// 修改子版面或合集的合并显示状态
const blockSubForum = (mirrorId: number, type: 'add' | 'del') => {
  const forumId = data.value?.forumId;
  if (!forumId) return
  forumStore.blockSubForum(forumId, mirrorId, type).then(res => {
    refresh()
  })
}

onMounted(async () => {
  await request(route, false);
  await forumStore.favorList()
})

watch(route, async (r) => {
  await request(r, false)
  showSubForumDialog.value = false
  showBlockedTopicDialog.value = false
})


// 快捷键
const shortKeys: ShortKey[] = [
  {title: '刷新', keys: ['alt', 'r'], action: refresh},
  ...scrollShortKeys,
  {title: '向左翻页', keys: ['a'], action: () => pageOffset(-1)},
  {title: '向右翻页', keys: ['d'], action: () => pageOffset(1)},
  {title: '翻到第一页', keys: ['shift', 'a'], action: () => changePage(1)},
]
</script>

<template>
  <!--快捷键-->
  <div class="short-key-div">
    <template v-for="k in shortKeys">
      <span v-shortkey="k.keys" @shortkey="k.action">{{ k.title }}</span>
    </template>
  </div>
  <div v-loading="loading" class="nav-bg-color route-root">
    <el-page-header @back="goBack">
      <template #content>
        <div>
          <el-image v-if="forumIcon" :src="forumIcon" style="width: 50px;height: 50px"/>
          <span v-if=" route.name===TopicListRoute.USER_TOPIC">用户发布的主题
            <span v-if="title"> 在 </span>

          </span>
          <span v-else-if="route.name===TopicListRoute.USER_REPLIES">用户发布的回复
            <span v-if="title"> 在 </span>
          </span>
          <span v-else-if="route.name==TopicListRoute.FORUM_SEARCH || route.name == TopicListRoute.COL_SEARCH">搜索结果</span>
          <span v-else-if="!data?.forumName">加载中...</span>
          <span v-if="title" class="clickable" @click="routeToForum"> {{ title }}</span>
          <span v-if="route.name==TopicListRoute.FORUM_RECOMMEND">[精华区]</span>
        </div>
      </template>
      <template #extra>
        <div>
          <el-button-group v-if="data" size="small">
            <el-button v-if="data?.data?.filter(i=>i.blocked)?.length" type="primary" @click="showBlockedTopicDialog=true">已屏蔽({{ data?.data?.filter(i => i.blocked)?.length }})
            </el-button>
            <el-button v-if="data.toppedTopicId" type="primary" @click="router.push({name:ReplyListRoute.LIST ,params:{tid:data.toppedTopicId}})">版头</el-button>
            <el-button v-if="data?.subForums" type="primary" @click="showSubForumDialog=true">子版 ({{ data.subForums.length }})</el-button>
            <el-button type="primary" @click="showShortKeys(shortKeys)">热键</el-button>
            <el-tooltip effect="light" placement="bottom" trigger="click">
              <el-button type="primary">搜索</el-button>
              <template #content>
                <el-input v-model="keyword" clearable placeholder="请输入关键字" @keyup.enter="routeToSearch"/>

                <div style="margin: 3px 3px">
                  <el-checkbox-group v-model="checkList" :min="1">
                    <el-checkbox v-if="data.forumId" :value="data.forumId">{{ data.forumName }}</el-checkbox>
                    <el-checkbox v-for="sub in data.subForums.filter(i=>i.type=='forum')" v-if="data.subForums" :value="sub.id">{{
                        sub.name
                      }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <div style="margin: 3px 3px">
                  <el-radio-group v-model="content">
                    <el-radio-button :value="SearchContent.Title" label="标题"/>
                    <el-radio-button :value="SearchContent.Content" label="正文"/>
                    <el-radio-button :value="SearchContent.Reply" label="回复"/>
                  </el-radio-group>
                </div>
                <el-switch v-model="recommend" :active-value="1" :inactive-value="0" active-text="仅精华"/>
                <el-button type="primary" @click="routeToSearch">搜索</el-button>
              </template>
            </el-tooltip>
            <el-button type="primary" @click="privilege">权限</el-button>
            <el-button v-if="route.name==TopicListRoute.FORUM_LIST" type="primary" @click="routeToRecommend">精华</el-button>
            <el-button v-if="forumStore.favorForums && forumStore.favorForums.find(i=>i.fid===Number(fid) || i.stid==stid)" type="danger" @click="favorDel(Number(fid),stid)">取关
            </el-button>
            <el-button v-else type="success" @click="favorAdd(Number(fid),stid)">关注</el-button>
            <el-button type="primary" @click="refresh">刷新</el-button>
            <el-button type="primary" @click="routeToPost(fid,stid)">发帖</el-button>
          </el-button-group>
        </div>
      </template>
    </el-page-header>
    <div v-if="data">
      <el-pagination :current-page="page" :page-size="data.size" :total="data.total?data.total:(page+5)*(data.size|| 20)"
                     layout="prev, pager, next,jumper, total"
                     @current-change="changePage"/>
    </div>
    <div>
      <topic-table v-if="data?.data" :show-parent="!stid" :topics="data?.data?.filter(i=>!i.blocked)"/>
    </div>
    <el-dialog v-model="showSubForumDialog" append-to-body class="bg-color" title="子版面 / 合集" width="80%">
      <div v-for="item in data?.subForums" style="display: inline-block;text-align: center">
        <forum-icon-name
            :fid="item.type==='forum'?item.id : undefined"
            :name="item.name"
            :stid="item.type==='col'?item.id : undefined"/>
        <br>

        <el-button v-if="!item.status.includes(ForumStatus.SELECTABLE)" disabled type="danger">不可修改</el-button>
        <el-button v-else-if="item.status.includes(ForumStatus.SELECTED_EXTRA) " type="success" @click="blockSubForum(item.mirrorId,'add')">已选中</el-button>
        <el-button v-else type="warning" @click="blockSubForum(item.mirrorId,'del')">未选中</el-button>
      </div>
    </el-dialog>

    <el-dialog v-model="showBlockedTopicDialog" append-to-body class="bg-color" title="被屏蔽主题" width="80%">
      <topic-table v-if="data?.data" :show-parent="!stid" :topics="data?.data?.filter(i=>i.blocked)"/>
    </el-dialog>

    <el-dialog v-model="showPrivilegeDialog" append-to-body class="bg-color" title="版面权限" width="80%">
      <div v-html="privilegeHtml"></div>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>